//
//  YJCWaveLineView.m
//  ProjectDemo
//
//  Created by IOS3 on 2018/12/10.
//  Copyright © 2018 IOS3. All rights reserved.
//

#import "YJCWaveLineView.h"


@interface YJCWaveLineView ()

@property (strong, nonatomic) CADisplayLink *displayLink;
@property (strong, nonatomic) CAShapeLayer *shapeLayer;
@property (strong, nonatomic) UIBezierPath *path;
@property (nonatomic, assign) CGFloat ω;


@end

@implementation YJCWaveLineView

- (void)startWithAngle:(CGFloat)ω fillColor:(UIColor *)fillColor {
    self.ω = ω;
    
    _shapeLayer = [CAShapeLayer layer];
    _shapeLayer.frame = self.bounds;
    [self.layer addSublayer:_shapeLayer];
    
    _shapeLayer.fillColor = fillColor.CGColor;
    _displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(drawPath)];
    [_displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}


- (void)drawPath {
    static double i = 0;
    CGSize size = self.frame.size;
    
    CGFloat A = size.height * 0.5;//A振幅
    CGFloat k = size.height * 0.5;//y轴偏移
    CGFloat ω = 0.01;//角速度ω变大，则波形在X轴上收缩（波形变紧密）；角速度ω变小，则波形在X轴上延展（波形变稀疏）。不等于0
    CGFloat φ = 0 + i;//初相，x=0时的相位；反映在坐标系上则为图像的左右移动。
    
    //y=Asin(ωx+φ)+k
    _path = [UIBezierPath bezierPath];
    [_path moveToPoint:CGPointZero];
    
    for (int i = 0; i < size.width; i ++) {
        CGFloat x = i;
        CGFloat y = A * sin(ω*x+φ)+k;
        [_path addLineToPoint:CGPointMake(x, y)];
    }
    
    [_path addLineToPoint:CGPointMake(size.width, size.height)];
    [_path addLineToPoint:CGPointMake(0, size.height)];
    _path.lineWidth = 1;
    _shapeLayer.path = _path.CGPath;
    
    i += 0.1;
    if (i > M_PI * 2) {
        i = 0;//防止i越界
    }
}

- (void)dealloc {
    [self.displayLink invalidate];
    self.displayLink = nil;
    
}


@end
